package cn.chiship.sdk.framework.multipartFile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 克隆流实体类
 *
 * @author lijian
 */
public class CloneInputStreams {

	private static final Logger LOGGER = LoggerFactory.getLogger(CloneInputStreams.class);

	InputStream inputStream1;

	InputStream inputStream2;

	public InputStream getInputStream1() {
		return inputStream1;
	}

	public void setInputStream1(InputStream inputStream1) {
		this.inputStream1 = inputStream1;
	}

	public InputStream getInputStream2() {
		return inputStream2;
	}

	public void setInputStream2(InputStream inputStream2) {
		this.inputStream2 = inputStream2;
	}

	/**
	 * 流克隆
	 * @param input 输入流
	 * @return ByteArrayOutputStream
	 */
	public static ByteArrayOutputStream cloneInputStream(InputStream input) {
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len;
			while ((len = input.read(buffer)) > -1) {
				baos.write(buffer, 0, len);
			}
			baos.flush();
			return baos;
		}
		catch (IOException e) {
			LOGGER.error("发生异常", e);
			return null;
		}
	}

	/**
	 * 获得克隆的数据流
	 * @param input 输入流
	 * @return CloneInputStreams
	 */
	public static CloneInputStreams getCloneInputStream(InputStream input) {
		ByteArrayOutputStream baos = cloneInputStream(input);
		InputStream stream1 = new ByteArrayInputStream(baos.toByteArray());
		InputStream stream2 = new ByteArrayInputStream(baos.toByteArray());

		CloneInputStreams cloneInputStreams = new CloneInputStreams();
		cloneInputStreams.setInputStream1(stream1);
		cloneInputStreams.setInputStream2(stream2);

		return cloneInputStreams;
	}

}
